import { createContext, useReducer, useContext, useEffect } from 'react';
import { UnitReducer } from './UnitReducer';
import {
  getTableDataList,
  addTableDataList,
  editTableDataItem,
  delTableDataItem
} from '@/api/archives/practice';
import {
  SET_TABLE_LIST,
  ADD_TABLE_ITEM,
  EDIT_TABLE_ITEM,
  EDL_TABLE_ITEM,
  CHANGE_PAGE,
  LOADING
} from './constants';

const initialState = {
  listQuery: {
    pageNo: 1,
    pageSize: 5,
    param: {
      businessType: 1,
      receiveType: 1
    }
  },
  loading: true,
  // table列表数据
  tableList: [],
  // 接收方式
  receiveModeList: [
    { id: 0, name: '离线接收' },
    { id: 1, name: '在线接收' }
  ],
  // 状态
  statusList: [
    { id: 0, name: '待上传' },
    { id: 1, name: '待入库' },
    { id: 2, name: '入库失败' },
    { id: 3, name: '已入库' },
    { id: 4, name: '已撤回' }
  ]
};

const UnitContext = createContext();

const UnitContextProvider = (props) => {
  console.log('UnitContextProvider');
  const [state, dispatch] = useReducer(UnitReducer, initialState);

  const actions = {
    // 查询table表格数据
    async queryTableList() {
      const res = await getTableDataList(state.listQuery);
      const { data } = res;
      dispatch({ type: SET_TABLE_LIST, data });
    },
    // 添加数据
    addTableListItem(payload) {
      return new Promise((resolve, reject) => {
        addTableDataList(payload)
          .then(({ data }) => {
            dispatch({ type: ADD_TABLE_ITEM, data });
            resolve();
          })
          .catch((err) => reject(err));
      });
    },
    // 编辑数据
    editTableItem(payload) {
      return new Promise((resolve, reject) => {
        editTableDataItem(payload)
          .then(({ data }) => {
            console.log('编辑结果返回：', data);
            const { id } = data;
            dispatch({ type: EDIT_TABLE_ITEM, data, id });
            resolve();
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 删除
    delTableItem(id) {
      return new Promise((resolve, reject) => {
        delTableDataItem(id)
          .then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: EDL_TABLE_ITEM, ids: data });
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 翻页
    setListQuery(info) {
      dispatch({ type: LOADING });
      dispatch({ type: CHANGE_PAGE, info });
    }
  };

  const filter = {
    receiveModeFilter(id) {
      return state.receiveModeList.find((item) => item.id === id)?.name || '-';
    },
    statusFilter(id) {
      return state.statusList.find((item) => item.id === id)?.name || '-';
    }
  };

  useEffect(() => {
    actions.queryTableList();
  }, [state.listQuery]);

  return (
    <UnitContext.Provider value={{ ...state, ...actions, ...filter }}>
      {props.children}
    </UnitContext.Provider>
  );
};

export const useUnitContext = () => {
  return useContext(UnitContext);
};

export { UnitContextProvider };
